﻿// <copyright file="TrackTouch.cs" company="Microsoft">
// Copyright (c) 2010 Microsoft All Rights Reserved
// </copyright>
// <author>Microsoft</author>
// <email>mischero@microsoft.com</email>
// <date>2010-02-12</date>
// <summary>Web analytics service behavior class definition</summary>

namespace Microsoft.WebAnalytics.Behaviors
{
    using System;
    using System.ComponentModel.Composition;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Interactivity;
    using Microsoft.WebAnalytics;

    /// <summary>
    /// <img src="../media/Microsoft.WebAnalytics.Behaviors.TrackTouch.24x24.png"/> 
    /// Track Touch.FrameReported events on Windows 7 touch-enabled systems, 
    /// logging the number of touch points in the AnalyticsEvent.Value property
    /// </summary>
    public class TrackTouch : Behavior<Panel>
    {
        #region Properties
        /// <summary>
        /// Gets or sets the event Logging method
        /// </summary>
        [Import("Log")]
        public Action<AnalyticsEvent> Log { get; set; }
        #endregion

        #region Methods
        /// <summary>
        /// Attach the Touch.FrameReported event and initialize parts
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();

            CompositionInitializerEx.SatisfyImports(this);

            Touch.FrameReported += new TouchFrameEventHandler(this.Touch_FrameReported);

            this.AssociatedObject.Unloaded += new RoutedEventHandler(delegate(object sender, RoutedEventArgs args)
            {
                System.Windows.Interactivity.Interaction.GetBehaviors(this.AssociatedObject).Remove(this);
            });
        }

        /// <summary>
        /// Detach events
        /// </summary>
        protected override void OnDetaching()
        {
            base.OnDetaching();

            Touch.FrameReported -= new TouchFrameEventHandler(this.Touch_FrameReported);
        }

        #endregion

        #region Implementation
        /// <summary>
        /// Track the Touch.FrameReported Event, sending the number of touch points in the Value
        /// </summary>
        /// <param name="sender">the associated object</param>
        /// <param name="e">the routed event arguments</param>
        private void Touch_FrameReported(object sender, TouchFrameEventArgs e)
        {
            var touchPoints = e.GetTouchPoints(this.AssociatedObject);

            // Initialize the AnalyticsEvent with parameters specific to the control event
            var logEvent = new AnalyticsEvent()
            {
                Name = "FrameReported",
                ObjectName = "Touch",
                Value = touchPoints.Count
            };

            // Log the event
            this.Log(logEvent);
        }
        #endregion
    }
}
